package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import ui.AddClient;
import ui.PrincipaleWindow;

public class FrameMain extends PrincipaleWindow {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	JPanel panel = new JPanel();
	JPanel panel_Button = new JPanel();
	JButton startServer = new JButton("Start Server");
	JButton add_client = new JButton("Add new Client");
	JTable list_torrent = new JTable();;
	private File file = new File("./torrent");
	private final FrameMain frameMain = this;
	private ServerMain server;
	private boolean serverDemarre;

	public FrameMain(){
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		panel_Button.add(startServer);
		panel_Button.add(add_client);
		final DefaultTableModel model = new DefaultTableModel();
		model.addColumn("Client");
		for (final File child : file.listFiles()){
			if (child.isDirectory()){
				model.addRow(new Object[] { child.getName() });
			}
		}
		list_torrent.setModel(model);
		startServer.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(final ActionEvent arg0) {
				server = new ServerMain();
				serverDemarre = server.getServerDemarrer();
			}
		});

		add_client.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(final ActionEvent e) {
				if (serverDemarre == true){
					new AddClient(frameMain);
				}
				else {
					ServerMain.serveurMessage("Lancer le serveur avant");
				}
			}
		});


		final JScrollPane scroll = new JScrollPane(list_torrent);
		panel.add(scroll);
		this.getContentPane().add("West", panel);
		this.getContentPane().add("East", panel_Button);
		this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}

	@Override
    public JTable getList_torrent() {
		return list_torrent;
	}

	@Override
    public File getFile() {
		return file;
	}

	@Override
    public void setFile(final File file) {
		this.file = file;
	}

	@Override
    public void setTableau(final JTable tableau) {
		this.list_torrent = tableau;
	}

	public static void main(final String[] args){
		new FrameMain();
	}

}

